package org.alis.smallcc.designpatterns.behavior.proxy.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Objects;

public class AopFactory implements InvocationHandler {

	private final Object obj;
	public AopFactory(Object obj) {
		this.obj = obj;
	}
	
	private Runnable beforeRun;

	private Runnable afterRun;

	public AopFactory bulidBeforeRun(Runnable run) {
		this.beforeRun = run;
		return this;
	}

	public AopFactory bulidAfterRun(Runnable run) {
		this.afterRun = run;
		return this;
	}
	
	public Object invok() {
		return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
	}

	
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		if(Objects.nonNull(beforeRun)) {
			this.beforeRun.run();
		}
		Object invoke = method.invoke(this.obj, args);
		if(Objects.nonNull(afterRun)) {
			this.afterRun.run();
		}
		return invoke;
	}

	@SuppressWarnings("unchecked")
	public static <T> T instance(Object obj,Runnable before,Runnable after) {
		AopFactory aopFactory = new AopFactory(obj);
		aopFactory.bulidBeforeRun(before).bulidAfterRun(after);
		return  (T)Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), aopFactory);
	}
	
	public static Object instanceT(Object obj,Runnable before,Runnable after) {
		AopFactory aopFactory = new AopFactory(obj);
		aopFactory.bulidBeforeRun(before).bulidAfterRun(after);
		return  Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), aopFactory);
	}
}
